<template>
  <el-form-item
    :label="label"
    :label-width="labelWidth"
    :prop="props.data.field"
    :required="props.data.required"
    :rules="props.data.rules"
  >
    <el-input
      class="__amount"
      v-model="val"
      :style="{ width: `${props.data.compWidth || 100}%` }"
      clearable
      :placeholder="props.data.placeholder"
      :prefix-icon="getIcon(props.data.prefixIcon)"
      :readonly="props.data.readonly"
      :disabled="props.data.disabled"
      @keydown="onKeydown"
      @input="onInput"
      @focus="onFocus"
      @blur="onBlur"
    >
      <template #append>元</template>
    </el-input>
  </el-form-item>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElFormItem, ElInput } from 'element-plus'
import { useElIcon } from '@/hooks/icon'
import { useProps } from '../../common-props/hooks'

const props = defineProps<{ data: Record<string, any>; form: Record<string, any> }>()
const emits = defineEmits(['valueChange'])

const { label, labelWidth } = useProps(props)
const { getIcon } = useElIcon()

const val = ref()

onMounted(() => {
  onBlur()
})

let preVal = ''
const onKeydown = (event: any) => {
  if (!props.data.minus && event.key == '-') {
    event.preventDefault()
  }
  preVal = val.value
}
const onInput = (_val: any) => {
  if (_val) {
    if (isNaN(parseFloat(_val)) || !isFinite(_val)) {
      val.value = preVal
    }
  }
}
const onFocus = () => {
  const _val = val.value
  if (_val) {
    val.value = val.value.replace(/¥|,|\s/g, '')
  }
}
const onBlur = () => {
  if (val.value) {
    const max = props.data.max
    if (max) {
      if (+val.value > +max) {
        val.value = +max
      }
    }
    const min = +props.data.min
    if (min) {
      if (+val.value < +min) {
        val.value = +min
      }
    }
    const numStr = round(val.value)
    let reg = numStr.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(\d{3})+$)/g
    val.value = `¥ ${numStr.replace(reg, '$1,')}`

    console.log(numStr)
    emits('valueChange', { name: props.data.field, value: numStr })
  }
}
const round = (_val: any) => {
  const num = +_val
  return (Math.round(num * 100) / 100).toFixed(2)
}
</script>

<style lang="scss" scoped>
:deep(.__amount) {
  input {
    text-align: center;
  }
}
</style>
